package com.platform.core.security.auth;

import com.platform.comm.util.CommonWriter;
import com.platform.comm.web.results.JsonResult;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 描述：访问未授权资源处理
 *
 * @author sunzhubin.zh
 */
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest,
                         HttpServletResponse httpServletResponse,
                         AuthenticationException e) throws IOException {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        JsonResult result = JsonResult.of();
        if (e instanceof BadCredentialsException) {
            CommonWriter.write(result.fail("用户名或密码错误"), httpServletResponse);
        } else {
            CommonWriter.write(result.fail("请登录"), httpServletResponse);
        }

    }
}
